package com.ihighest.app.infox.activity;

import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult.AddressComponent;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.myview.ActivityTitle;

/**
 * 选择地图标记，支持startActivityForResult方式调用 result
 * 
 * <pre>
 *  入参数：
 *  current true | false 显示当前位置，默认为true
 *  lat 指定位置经度
 *  lon 指定位置纬度
 *  
 *  返回值
 *  addr 详细地址
 *  info 商圈信息
 *  lat  选中位置经度
 *  lon  选中位置纬度
 * 
 * </pre>
 * 
 * @author Vity Created at 2015-11-3 下午9:22:45
 * @version 1.0
 */
public class MapMarkerActivity extends BaseActivity {

	private static final String TAG = "MapMarkerActivity";

	ActivityTitle title;

	MapView mapView;
	BaiduMap baiduMap;
	Marker marker;
	BitmapDescriptor bitmap;
	GeoCoder geoCoder;
	ReverseGeoCodeOption reverseGeoCodeOption;

	Intent intentResult;
	double lat, lon;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SDKInitializer.initialize(getApplicationContext());
		setContentView(R.layout.infox_activity_mymap);
		initView();
		initMap();
	}

	private void initView() {
		title = (ActivityTitle) findViewById(R.id.mActivityTitle);
		title.setViewVersible(title.titleBack, title.rightText, title.top_title_text);
		title.setViewGone(title.titleMsg, title.titleRefresh, title.rightLayout);
		title.setTitle("地图");
		title.rightText.setText("确定");
		title.rightText.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				setResult(RESULT_OK, intentResult);
				finish();
			}
		});
		title.titleBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				setResult(RESULT_CANCELED);
				finish();
			}
		});

		mapView = (MapView) this.findViewById(R.id.bmapView); // 获取地图控件引用
		baiduMap = mapView.getMap();
		// 开启定位图层
		baiduMap.setMyLocationEnabled(true);
		// 设置定位图层的配置（定位模式，是否允许方向信息，用户自定义定位图标）
		MyLocationConfiguration config = new MyLocationConfiguration(LocationMode.NORMAL, true,
				BitmapDescriptorFactory.fromResource(R.drawable.infox_location_img));
		baiduMap.setMyLocationConfigeration(config);
		baiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {

			@Override
			public boolean onMapPoiClick(MapPoi poi) {
				return false;
			}

			@Override
			public void onMapClick(LatLng point) {
				marker(point.latitude, point.longitude);
			}
		});

		if (getIntent().getBooleanExtra("current", true)) {

			// 显示当前
			JSONObject loc = SharedPreferencesKit.getJsonObject(this, Const.SP_KEY_BD_LOCAITON);
			if (loc != null) {
				try {
					LatLng cenpt = new LatLng(loc.getDouble("latitude"), loc.getDouble("lontitude"));
					// 定义地图状态
					MapStatus mMapStatus = new MapStatus.Builder().target(cenpt).zoom(18).build();
					// 定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
					MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
					// 改变地图状态
					baiduMap.setMapStatus(mMapStatusUpdate);
					marker(loc.getDouble("latitude"), loc.getDouble("lontitude"));
				} catch (Exception e) {
					Log.e(TAG, e.getMessage(), e);
				}
			}
		} else {
			// 显示指定
			lat = getIntent().getDoubleExtra("lat", -1);
			lon = getIntent().getDoubleExtra("lon", -1);
			if (lat != -1 && lon != -1) {
				LatLng cenpt = new LatLng(lat, lon);
				// 定义地图状态
				MapStatus mMapStatus = new MapStatus.Builder().target(cenpt).zoom(18).build();
				// 定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
				MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
				// 改变地图状态
				baiduMap.setMapStatus(mMapStatusUpdate);
				marker(lat, lon);
			}
		}
	}

	private void initMap() {

	}

	private void marker(double lat, double lon) {
		this.lat = lat;
		this.lon = lon;
		loction();
		if (marker != null) {
			marker.remove();
			marker = null;
		}
		LatLng point = new LatLng(lat, lon);
		// 构建Marker图标
		BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.infox_location_img);
		// 构建MarkerOption，用于在地图上添加Marker
		OverlayOptions option = new MarkerOptions().position(point).icon(bitmap).draggable(true);
		// 在地图上添加Marker，并显示
		marker = (Marker) (baiduMap.addOverlay(option));
	}

	private void loction() {
		// 创建GeoCoder实例对象
		geoCoder = GeoCoder.newInstance();
		// 发起反地理编码请求(经纬度->地址信息)
		reverseGeoCodeOption = new ReverseGeoCodeOption();
		// 设置反地理编码位置坐标
		reverseGeoCodeOption.location(new LatLng(lat, lon));
		geoCoder.reverseGeoCode(reverseGeoCodeOption);

		// 设置查询结果监听者
		geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {

			@Override
			public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
				AddressComponent ac = reverseGeoCodeResult.getAddressDetail();
				intentResult = new Intent();
				intentResult.putExtra("info", reverseGeoCodeResult.getBusinessCircle());
				intentResult.putExtra("addr", (ac.province + ac.city + ac.district + ac.street + ac.streetNumber).replace(" ", "").trim());
				intentResult.putExtra("lat", reverseGeoCodeResult.getLocation().latitude);
				intentResult.putExtra("lon", reverseGeoCodeResult.getLocation().longitude);
			}

			@Override
			public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
				// pass
			}
		});
	}

	// 三个状态实现地图生命周期管理
	@Override
	protected void onDestroy() {
		baiduMap.setMyLocationEnabled(false);
		super.onDestroy();
		mapView.onDestroy();
		mapView = null;
	}

	@Override
	protected void onResume() {
		super.onResume();
		mapView.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
		mapView.onPause();
	}
}
